package com.heima.wemedia.controller.v1;

import com.alibaba.fastjson.JSON;
import com.heima.client.article.IArticleClient;
import com.heima.model.common.dtos.NewsPageDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.listener.CommentListener;
import com.heima.wemedia.service.ReportService;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/v1/statistics")
public class WmReportController {

    @Autowired
    private ReportService reportService;

    @Autowired
    private IArticleClient articleClient;

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;
    @Autowired
    private CommentListener commentListener;

    /**
     * 图文统计
     *
     * @param beginDate
     * @param endDate
     * @return
     */
    @GetMapping("/newsDimension")
    public ResponseResult viewReport(
            @RequestParam(value = "beginDate", required = false) String beginDate,
            @RequestParam(value = "endDate", required = false) String endDate
    ) {
        log.info("接收到参数：{},{}", beginDate, endDate);
        //将字符串类型转为时间类
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE;//定义格式器
        // 使用字符串转换为LocalDate
        LocalDate begin = LocalDate.parse(beginDate, formatter);
        LocalDate end = LocalDate.parse(endDate, formatter);
        return reportService.viewReport(begin, end);
    }


    /**
     * 分页展示文章列表
     *
     * @param newsPageDto
     * @return
     */
    @GetMapping("/newsPage")
    public ResponseResult newsPage(@DateTimeFormat(pattern = "yyyy-MM-dd") Date beginDate,
                                   @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
                                   Integer page, Integer size) {
        Integer userId = WmThreadLocalUtil.get();
        NewsPageDto newsPageDto = new NewsPageDto();
        newsPageDto.setBeginDate(beginDate);
        newsPageDto.setEndDate(endDate);
        newsPageDto.setPage(page);
        newsPageDto.setSize(size);
        log.info("接收分页参数：{}", newsPageDto);
        newsPageDto.setWmUserId(userId);
        //kafkaTemplate.send("article_list", JSON.toJSONString(newsPageDto));
        ResponseResult result = articleClient.newsPage(newsPageDto);
        return result;
    }
}
